const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g // {{}}
/** 将ast变成render */
function genProps(attrs){
  let str = '';
  for (let i = 0; i< attrs.length; i++){
    let attr = attrs[i];
    if (attr.name === 'style') {
      let obj = {};
      // style="color: #000; font-size: 20px;"
      attr.value.split(';').forEach(item => {
        if (!item) return;
        let [key, value] = item.split(':');
        obj[key.trim()] = value.trim();
      });
      attr.value = obj;
    }
    // 拼接
    str += `${attr.name}:${JSON.stringify(attr.value)},`
  }
  return `{${str.slice(0, -1)}}`
}

function genChildren(el){
  let children = el.children;
  if (children) {
    return children.map(child => gen(child)).join(',')
  }
}
function gen(node){
  // 1：元素 3：文本
  if (node.type === 1) {
    return generate(node)
  } else {
    // 1, 只是文本，2, 插值表达式{{}}
    let text = node.text;
    if (!defaultTagRE.test(text)) {
      return `_v(${JSON.stringify(text)})`
    }
    // 带有{{}}
    let tokens = [];
    // 置为0，不然匹配不到
    let lastIndex = defaultTagRE.lastIndex = 0;
    let match;
    while (match = defaultTagRE.exec(text)) {
      let index = match.index;
      if (index > lastIndex) {
        //  添加内容
        tokens.push(JSON.stringify(text.slice(lastIndex, index)))
      }
      tokens.push(`_s(${match[1].trim()})`);
      lastIndex = index + match[0].length;
    }
    if (lastIndex < text.length) {
      tokens.push(JSON.stringify(text.slice(lastIndex)));
    }
    return `_v(${tokens.join('+')})`
  }
}
// render(){
//   return _c('div', {id: 'app', style: {}}, _v('hello' + _s(msg)), _c())
// }
export function generate(el){
  let children = genChildren(el);
  let code = `_c('${el.tag}',${el.attrs.length ? genProps(el.attrs) : 'undefined'}${children ? `,${children}` : ''})`;
  return code
}